package com.hiultra.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hiultra.archive.domain.*;
import com.hiultra.archive.domain.vo.ArchiveDesTaskIssuedVo;
import com.hiultra.archive.domain.vo.HouseLocationNoInfoIssuedVo;
import com.hiultra.archive.domain.vo.ResultEntity;
import com.hiultra.archive.mapper.ArchiveArchAreaMapper;
import com.hiultra.archive.service.IArchiveArchAreaService;
import com.hiultra.archive.service.IArchiveCabinetService;
import com.hiultra.archive.utils.sgsm.SM2Util;
import com.hiultra.archive.utils.tool.ToolUtils;
import com.hiultra.common.constant.BusinessConstants;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 区Service业务层处理
 *
 * @author paidaxing
 * @date 2024-07-25
 */
@Service
public class ArchiveArchAreaServiceImpl implements IArchiveArchAreaService {
    private static final Logger log = LoggerFactory.getLogger(ArchiveDesTaskServiceImpl.class);

    @Value("${roomNo}")
    private String roomNo;
    @Value("${priKey}")
    private String priKey;
    @Autowired
    private ArchiveArchAreaMapper archiveArchAreaMapper;
    @Autowired
    private IArchiveCabinetService archiveCabinetService;

    /**
     * 查询区
     *
     * @param id 区主键
     * @return 区
     */
    @Override
    public ArchiveArchArea selectArchiveArchAreaById(String id) {
        return archiveArchAreaMapper.selectArchiveArchAreaById(id);
    }

    /**
     * 查询区列表
     *
     * @param archiveArchArea 区
     * @return 区
     */
    @Override
    public List<ArchiveArchArea> selectArchiveArchAreaList(ArchiveArchArea archiveArchArea) throws JsonProcessingException {
        return archiveArchAreaMapper.selectArchiveArchAreaList(archiveArchArea);
    }

    /**
     * 新增区
     *
     * @param archiveArchArea 区
     * @return 结果
     */
    @Override
    public int insertArchiveArchArea(ArchiveArchArea archiveArchArea) {
        archiveArchArea.setCreateTime(DateUtils.getNowDate());
        return archiveArchAreaMapper.insertArchiveArchArea(archiveArchArea);
    }

    /**
     * 修改区
     *
     * @param archiveArchArea 区
     * @return 结果
     */
    @Override
    public int updateArchiveArchArea(ArchiveArchArea archiveArchArea) {
        return archiveArchAreaMapper.updateArchiveArchArea(archiveArchArea);
    }

    /**
     * 批量删除区
     *
     * @param ids 需要删除的区主键
     * @return 结果
     */
    @Override
    public int deleteArchiveArchAreaByIds(String[] ids) {
        return archiveArchAreaMapper.deleteArchiveArchAreaByIds(ids);
    }

    /**
     * 删除区信息
     *
     * @param id 区主键
     * @return 结果
     */
    @Override
    public int deleteArchiveArchAreaById(String id) {
        return archiveArchAreaMapper.deleteArchiveArchAreaById(id);
    }

    /**
     * 库位信息下发接口
     *
     * @param data 区
     * @return 结果
     */
    @Override
    public ResultEntity insertIssuedArchiveArchArea(String data) {
        //解密
        System.out.println("库位下发入参" + data);
        String decryptedResult = new SM2Util().decryptBySM2(data, priKey);
        System.out.println("库位下发解密结果：" + decryptedResult);
        HouseLocationNoInfoIssuedVo houseLocationNoInfoVo = JSON.parseObject(decryptedResult.trim(), HouseLocationNoInfoIssuedVo.class);

        if (ObjectUtil.isNull(houseLocationNoInfoVo)) {
            // 返回错误信息或抛出异常
            log.info("入参解析出错，请检查重试");
            return ResultEntity.error("入参解析出错，请检查重试");
        }
        try {
            processArchiveArchArea(houseLocationNoInfoVo);
        } catch (ServiceException e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
        return ResultEntity.success();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void processArchiveArchArea(HouseLocationNoInfoIssuedVo houseLocationNoInfoVo) throws ServiceException {
        try {
            //新增档案区功能
            ArchiveArchArea archiveArchArea = new ArchiveArchArea();
            for (HouseLocationNoInfoIssuedVo.ArchArea area : houseLocationNoInfoVo.getArchAreaList()) {
                //判空
                archiveArchArea.setId(area.getArchareaId());
                archiveArchArea.setArchAreaNo(area.getArchAreaNo());
                archiveArchArea.setArchType(area.getArchType());
                //开柜方向，默认向右
                archiveArchArea.setOpenDirection(BusinessConstants.OPEN_DIRECTION_LEFT);
                //状态
                archiveArchArea.setStatus(BusinessConstants.SHELVES_STATUS_NO);

                //其他信息
                archiveArchArea.setArchivesRoomNo(houseLocationNoInfoVo.getRoomNo());

                ArchiveCabinet archiveCabinet = new ArchiveCabinet();
                for (HouseLocationNoInfoIssuedVo.Cabinet cabinet : area.getCabinetList()) {
                    //查询是否存在，如果存在则修改，不存在则新增
                    archiveCabinet.setId(cabinet.getCabinetId());
                    archiveCabinet.setArchivesRoomNo(houseLocationNoInfoVo.getRoomNo());
                    archiveCabinet.setOrgNo(houseLocationNoInfoVo.getOrgNo());
                    archiveCabinet.setArchiveAreaNo(area.getArchAreaNo());
                    archiveCabinet.setColNo(cabinet.getCabinetNo());
                    archiveCabinet.setSecNum(cabinet.getSecNum());
                    archiveCabinet.setLayNum(cabinet.getLayNum());
                    archiveCabinet.setBoxNum(cabinet.getBoxNum());
                    archiveCabinet.setParentColNo(area.getArchAreaNo());
                    archiveCabinet.setIsFixedCol(BusinessConstants.IS_NOT_FIXED_COL);
                    archiveCabinet.setIsOpen(BusinessConstants.IS_NOT_OPEN);
                    archiveCabinet.setType(BusinessConstants.CABINET_TYPE_COL);
                    archiveCabinet.setOpenDirection(BusinessConstants.OPEN_DIRECTION_LEFT);
                    //operType新增
                    if (BusinessConstants.LOCATION_OPERTYPE_ADD.equals(houseLocationNoInfoVo.getOperType())) {
                        if (ObjectUtil.isEmpty(archiveCabinetService.selectArchiveCabinetById(cabinet.getCabinetId()))) {
                            archiveCabinetService.insertArchiveCabinet(archiveCabinet);
                        }
                    } else {
                        if (ObjectUtil.isNotEmpty(archiveCabinetService.selectArchiveCabinetById(cabinet.getCabinetId()))) {
                            archiveCabinetService.updateArchiveCabinet(archiveCabinet);
                        }
                    }
                }
                if (BusinessConstants.LOCATION_OPERTYPE_ADD.equals(houseLocationNoInfoVo.getOperType())) {
                    if (ObjectUtil.isEmpty(selectArchiveArchAreaByArchAreaNo(archiveArchArea.getArchAreaNo()))) {
                        insertArchiveArchArea(archiveArchArea);
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(selectArchiveArchAreaByArchAreaNo(archiveArchArea.getArchAreaNo()))) {
                        updateArchiveArchArea(archiveArchArea);
                    }
                }
            }
        } catch (ServiceException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException("发生未知异常，事务已回滚"+e.getMessage());
        }
    }

    /**
     * 通过区号查询区
     *
     * @param archAreaNo 区号
     * @return 区
     */
    @Override
    public ArchiveArchArea selectArchiveArchAreaByArchAreaNo(String archAreaNo) {
        return archiveArchAreaMapper.selectArchiveArchAreaByArchAreaNo(archAreaNo);
    }
}
